# Mute Warnings (change in production environments)
mute_warnings = False
MYGL_RESIZE_SURFACE_POW2 = 0

# Import Errors
# import logging, traceback
# from mylib.glLib.glLibError import *

import math

# Import OpenGL
try:
    import OpenGL
    from OpenGL.GL import *
    from OpenGL.GLU import *
    '''
    from OpenGL.GLUT import *

    try: glutInit()
    except:
        if not mute_warnings: print("Warning: OpenGL.GLUT initialization failed")
    '''
    print('Import OpenGL(GL, GLU)')
except:
    raise GLError("Error: PyOpenGL not available")

# Import PyGame
try:
    import pygame
    from pygame.locals import *
    print('Import pygame')
except:
    raise GLError("Error: PyGame not available")

# Import NumPy
try:
    import numpy as np
    print('Import numpy')
    try:
        pygame.surfarray.use_arraytype("numpy")
        MYGL_AVAILABLE_SURFARRAY = True
    except:
        if not mute_warnings: print("Warning: Surfarray not available")
        MYGL_AVAILABLE_SURFARRAY = False
except:
    raise GLError("Error: NumPy not available")

# Import PIL
try:
    import PIL.Image as Image
    print('Import PIL')
except ImportError:
    if not mute_warnings: print("Warning: PIL.Image not available")

# Import Shaders
MYGL_AVAILABLE_SHADERS = False
try:
    from OpenGL.GL.ARB.shader_objects import *
    glInitShaderObjectsARB()
    from OpenGL.GL.ARB.vertex_shader import *
    glInitVertexShaderARB()
    from OpenGL.GL.ARB.fragment_shader import *
    glInitFragmentShaderARB()

    MYGL_AVAILABLE_SHADERS = True
    print('Import GL.ARB - Shader')
    try:
        from OpenGL.GL.ARB.geometry_shader4 import *
        glInitGeometryShader4ARB()
        print('Import GL.ARB - Shader(geometry)')
    except ImportError:
        if not mute_warnings: print("No geometry shaders")
except ImportError:
    if not mute_warnings: print("Warning: Shaders not available")

MYGL_AVAILABLE_FOG_COORD = False
try:
    from OpenGL.GL.EXT.fog_coord import *
    glInitFogCoordEXT()
    MYGL_AVAILABLE_FOG_COORD = True
    print('Import GL.EXT - Fog Coord')
except ImportError:
    if not mute_warnings: print("Warning: fog_coord not available")

# Import FBO Extension
MYGL_AVAILABLE_FRAMEBUFFERS = False
MYGL_AVAILABLE_MULTISAMPLE_FRAMEBUFFERS = False
try:
    from OpenGL.GL.EXT.framebuffer_object import *
    glInitFramebufferObjectEXT()
    MYGL_AVAILABLE_FRAMEBUFFERS = True
    print('Import GL.EXT - FrameBuffer')
    try:
        from OpenGL.GL.EXT.framebuffer_multisample import *
        glInitFramebufferMultisampleEXT()
        MYGL_AVAILABLE_MULTISAMPLE_FRAMEBUFFERS = True
        print('Import GL.EXT - FrameBuffer(multisample)')
    except ImportError:
        if not mute_warnings: print("Warning: Multisample FBOs not available")
except ImportError:
    if not mute_warnings: print("Warning: FBOs not available")

MYGL_AVAILABLE_MULTI_TEXTURES = False
try:
    from OpenGL.GL.ARB.multitexture import *
    glInitMultitextureARB()
    MYGL_AVAILABLE_MULTI_TEXTURES = True
    print('Import GL.ARB - MultiTexture')
except ImportError:
    if not mute_warnings: print("Warning: Multi textures not available")

# Import 32 Bit Float (High Precision) Textures
MYGL_AVAILABLE_FLOAT_TEXTURES = False
try:
    from OpenGL.GL.ARB.texture_float import *
    glInitTextureFloatARB()
    MYGL_AVAILABLE_FLOAT_TEXTURES = True
    print('Import GL.ARB - TextureFloat')
except ImportError:
    if not mute_warnings: print("Warning: High-precision textures not available")

# Import depth-stencil packed renderbuffer attachments
try:
    from OpenGL.GL.EXT.packed_depth_stencil import *
    print('Import GL.EXT - PackedDepthStencil')
except ImportError:
    if not mute_warnings: print("Warning: Depth-stencil packed renderbuffers are not available for FBOs")

# Import VBOs
MYGL_AVAILABLE_VBO = False
try:
    from OpenGL.arrays import vbo
    from OpenGL.GL.ARB.vertex_buffer_object import *
    glInitVertexBufferObjectARB()
    MYGL_AVAILABLE_VBO = True
    print('Import GL.ARB - VertexBufferObject')
except ImportError:
    if not mute_warnings: print("Warning: VBOs not available")

# Import Anisotropy
MYGL_AVAILABLE_ANISOTROPY = False
try:
    from OpenGL.GL.EXT.texture_filter_anisotropic import *
    MYGL_AVAILABLE_ANISOTROPY = True
    print('Import GL.EXT - TextureFilterAnisotropic')
except ImportError:
    if not mute_warnings: print("Warning: Anisotropic filtering not available")

# Import Hardware Occlusion Queries (for radiosity)
# try:
#     from OpenGL.GL.ARB.occlusion_query import *
# except:
#     if not mute_warnings: print "Warning: Hardware occlusion not available"

# Import Other
# import sys, os, bz2, time, zlib

try:
    import cPickle as pickle
except ImportError:
    import pickle as pickle

# Locals
#   Misc (1-100)
MYGL_3D = 1
MYGL_2D = 2
MYGL_FALSE = False
MYGL_TRUE = True
MYGL_NONE = None
MYGL_FBCOPY = 3
MYGL_USING_SHADER = False
MYGL_MAX = 4
MYGL_AUTO = 5
MYGL_CENTER = 6
MYGL_ALL = 7
MYGL_OLD = 8
MYGL_IDENTITY_MATRIX = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]
MYGL_LEFT = 9
MYGL_RIGHT = 10
MYGL_BOTTOM = 11
MYGL_TOP = 12
MYGL_FRONT = 13
MYGL_BACK = 14
#   Filters (101-200)
MYGL_GAUSS = 101
MYGL_BLOOM = 102
MYGL_BOX = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
MYGL_LAPLACIAN = [[0, -1, 0], [-1, 4, -1], [0, -1, 0]]
MYGL_SHARPEN = [[0, -1, 0], [-1, 5, -1], [0, -1, 0]]
MYGL_DOUBLE_LINE_SHARPEN = [[0, -1, -1, -1, 0], [-1, 2, -4, 2, -1], [-1, -4, 13, -4, -1], [-1, 2, -4, 2, -1],
                            [0, -1, -1, -1, 0]]
#   Draw Type (201-300)
MYGL_FILL = 201
MYGL_LINE = 202
MYGL_OUTLINE = 203
MYGL_POINT = 204
#   Lighting (301-400)
MYGL_VERTEX_NORMALS = 301
MYGL_FACE_NORMALS = 302
MYGL_POINT_LIGHT = 303
MYGL_DIRECTIONAL_LIGHT = 304
# MYGL_SINGLE_SIDE = 305
# MYGL_DOUBLE_SIDE = 306
#   Texturing (401-500)
MYGL_MIPMAP = 401
MYGL_MIPMAP_BLEND = 402
MYGL_FILTER = 403
MYGL_CLAMP = 404
MYGL_REPEAT = 405
MYGL_MIRROR_REPEAT = 406
MYGL_TEXTURE_1D = GL_TEXTURE_1D
MYGL_TEXTURE_2D = GL_TEXTURE_2D
MYGL_TEXTURE_3D = GL_TEXTURE_3D
MYGL_TEXTURE_CUBE = GL_TEXTURE_CUBE_MAP
MYGL_TEXTURE_CUBE_FACES = [GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
                           GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
                           GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z]
#       Formats
MYGL_RGB = GL_RGB
MYGL_RGBA = GL_RGBA
MYGL_DEPTH = GL_DEPTH_COMPONENT
#   Colors (501-600)
MYGL_RED = 502
MYGL_ORANGE = 503
MYGL_YELLOW = 504
MYGL_GREEN = 505
MYGL_BLUE = 506
MYGL_PURPLE = MYGL_VIOLET = 507
MYGL_MAGENTA = 508
MYGL_WHITE = 509
MYGL_BLACK = 510
MYGL_GREY = MYGL_GRAY = 511
MYGL_PINK = 512
MYGL_CYAN = 513
#   Shaders (601-700)
MYGL_PHONG = 601
MYGL_BLINN = 602
MYGL_TEXTURE = 603
MYGL_VIEW_DEPTHBUFFER = 604
MYGL_VIEW_NORMALS = 605
MYGL_BLANK = 606
MYGL_DEPTH_PEEL = 607
MYGL_DEPTH_PEEL_TYPES = 608
MYGL_DEPTH_PEEL_TRANSPARENT = 609
MYGL_DEPTH_PEEL_SINGLE_PASS = 610
MYGL_POSITION_NORMAL_MAP = 611
MYGL_CAUSTIC_MAP = 612
MYGL_PARTICLE_DRAW = 613
MYGL_PARTICLE_UPDATE = 614
MYGL_CLOTH_DISTANCE = 615
MYGL_CLOTH_UPDATE = 616
MYGL_CLOTH_COLLIDE = 617
MYGL_CLOTH_NORMAL = 618
MYGL_CLOTH_DRAW = 619
MYGL_HAIR_GROW = 620
MYGL_HAIR_UPDATE = 621
MYGL_HAIR_DRAW = 622
# MYGL_FLUID2D_DIFFUSE = 623
# MYGL_FLUID2D_ADVECT = 624
# MYGL_FLUID3D_UPDATE = 625
# MYGL_FLUID3D_DRAW = 626
MYGL_SOFTPHYS_UPDATE = 627
MYGL_SOFTPHYS_COLLIDE = 628
MYGL_SOFTPHYS_ADDFORCE = 629
MYGL_INTERNAL_VOLUME_RAY = 630
MYGL_INTERNAL_VOLUME_DRAW = 631
#   Obstacles (701-800)
MYGL_OBSTACLE_POLYGONAL = 701
MYGL_OBSTACLE_SPHERE = 702
MYGL_OBSTACLE_BOX = 703
#   Characters (801-900)
MYGL_MALE = 801
MYGL_FEMALE = 802
MYGL_CHARACTER_LEFTHIP = 803
MYGL_CHARACTER_RIGHTHIP = 804
MYGL_CHARACTER_LEFTKNEE = 805
MYGL_CHARACTER_RIGHTKNEE = 806
MYGL_CHARACTER_LEFTANKLE = 807
MYGL_CHARACTER_RIGHTANKLE = 808
MYGL_CHARACTER_PELVIS = 809
MYGL_CHARACTER_BACK = 810
MYGL_CHARACTER_LEFTSHOULDER = 811
MYGL_CHARACTER_RIGHTSHOULDER = 812
MYGL_CHARACTER_LEFTELBOW = 813
MYGL_CHARACTER_RIGHTELBOW = 814
#   Clothes (901-1000)
MYGL_CLOTHES_SHORTS = 901
MYGL_CLOTHES_LONGPANTS = 902
MYGL_CLOTHES_SKIRT = 903
MYGL_CLOTHES_DRESS = 904
MYGL_CLOTHES_SHIRT = 905
MYGL_CLOTHES_STRAPLESSTOP = 906
MYGL_CLOTHES_BUTTONSHIRT = 907
MYGL_CLOTHES_COAT = 908
MYGL_CLOTHES_SUITJACKET = 909
MYGL_CLOTHES_TRENCHCOAT = 910
MYGL_CLOTHES_CAPE = 911
MYGL_CLOTHES_CLOAK = 912
MYGL_CLOTHES_NECKTIE = 913
MYGL_CLOTHES_BOWTIE = 914
MYGL_CLOTHES_SCARF = 915
#   Radiosity (1001-1100)
MYGL_RADIOSITY_RATIO = 1001
MYGL_RADIOSITY_ITERATIONS = 1002

#   Materials
MYGL_MATERIAL_FULL = "MYGL Material Full"
MYGL_MATERIAL_BRASS = "MYGL Material Brass"
MYGL_MATERIAL_BRONZE = "MYGL Material Bronze"
MYGL_MATERIAL_CHROME = "MYGL Material Chrome"
MYGL_MATERIAL_COPPER = "MYGL Material Copper"
MYGL_MATERIAL_DEFAULT = "MYGL Material Default"
MYGL_MATERIAL_GOLD = "MYGL Material Gold"
MYGL_MATERIAL_SILVER = "MYGL Material Silver"
MYGL_MATERIAL_BLACK_PLASTIC = "MYGL Material Black Plastic"
MYGL_MATERIAL_CYAN_PLASTIC = "MYGL Material Cyan Plastic"
MYGL_MATERIAL_GREEN_PLASTIC = "MYGL Material Green Plastic"
MYGL_MATERIAL_RED_PLASTIC = "MYGL Material Red Plastic"
MYGL_MATERIAL_WHITE_PLASTIC = "MYGL Material White Plastic"
MYGL_MATERIAL_YELLOW_PLASTIC = "MYGL Material Yellow Plastic"
MYGL_MATERIAL_BLACK_RUBBER = "MYGL Material Black Rubber"
MYGL_MATERIAL_CYAN_RUBBER = "MYGL Material Cyan Rubber"
MYGL_MATERIAL_GREEN_RUBBER = "MYGL Material Green Rubber"
MYGL_MATERIAL_RED_RUBBER = "MYGL Material Red Rubber"
MYGL_MATERIAL_WHITE_RUBBER = "MYGL Material White Rubber"
MYGL_MATERIAL_YELLOW_RUBBER = "MYGL Material Yellow Rubber"
MYGL_MATERIAL_AMBIENT = "MYGL Material Ambient"
MYGL_MATERIAL_DIFFUSE = "MYGL Material Diffuse"
MYGL_MATERIAL_SPECULAR = "MYGL Material Specular"
MYGL_MATERIAL_NONE = "MYGL Material None"
MYGL_MATERIAL_EMERALD = "MYGL Material Emerald"
MYGL_MATERIAL_JADE = "MYGL Material Jade"
MYGL_MATERIAL_OBSIDIAN = "MYGL Material Obsidian"
MYGL_MATERIAL_PEARL = "MYGL Material Pearl"
MYGL_MATERIAL_RUBY = "MYGL Material Ruby"
MYGL_MATERIAL_TURQUOISE = "MYGL Material Turquoise"
MYGL_MATERIAL_GLASS = "MYGL Material Glass"


def get_material_param(material):
    # Metals
    if material == MYGL_MATERIAL_BRASS:
        material_parameters = (
            [0.329412, 0.223529, 0.027451], [0.780392, 0.568627, 0.113725], [0.992157, 0.941176, 0.807843], 27.89743616)
    elif material == MYGL_MATERIAL_BRONZE:
        material_parameters = ([0.2125, 0.1275, 0.054], [0.714, 0.4284, 0.18144], [0.393548, 0.271906, 0.166721], 25.6)
    elif material == MYGL_MATERIAL_CHROME:
        material_parameters = ([0.25, 0.25, 0.25], [0.4, 0.4, 0.4], [0.774597, 0.774597, 0.774597], 76.8)
    elif material == MYGL_MATERIAL_COPPER:
        material_parameters = (
            [0.19125, 0.0735, 0.0225, 1.0], [0.7038, 0.27048, 0.0828, 1.0], [0.256777, 0.137622, 0.086014, 1.0], 12.8)
    elif material == MYGL_MATERIAL_GOLD:
        material_parameters = (
            [0.24725, 0.1995, 0.0745, 1.0], [0.75164, 0.60648, 0.22648, 1.0], [0.628281, 0.555802, 0.366065, 1.0], 51.2)
    elif material == MYGL_MATERIAL_SILVER:
        material_parameters = (
            [0.19225, 0.19225, 0.19225, 1.0], [0.50754, 0.50754, 0.50754, 1.0], [0.508273, 0.508273, 0.508273, 1.0],
            51.2)
    # Plastics
    elif material == MYGL_MATERIAL_BLACK_PLASTIC:
        material_parameters = ([0, 0, 0, 1], [0.01, 0.01, 0.01, 1], [0.50, 0.50, 0.50, 1], 32)
    elif material == MYGL_MATERIAL_CYAN_PLASTIC:
        material_parameters = (
            [0.0, 0.1, 0.06], [0.0, 0.50980392, 0.50980392], [0.50196078, 0.50196078, 0.50196078], 32)
    elif material == MYGL_MATERIAL_GREEN_PLASTIC:
        material_parameters = ([0.0, 0.0, 0.0], [0.1, 0.35, 0.1], [0.45, 0.55, 0.45], 32)
    elif material == MYGL_MATERIAL_RED_PLASTIC:
        material_parameters = ([0.0, 0.0, 0.0], [0.5, 0.0, 0.0], [0.7, 0.6, 0.6], 32)
    elif material == MYGL_MATERIAL_WHITE_PLASTIC:
        material_parameters = ([0.0, 0.0, 0.0], [0.55, 0.55, 0.55], [0.70, 0.70, 0.70], 32)
    elif material == MYGL_MATERIAL_YELLOW_PLASTIC:
        material_parameters = ([0.0, 0.0, 0.0], [0.5, 0.5, 0.0], [0.60, 0.60, 0.50], 32)
    # Rubbers
    elif material == MYGL_MATERIAL_BLACK_RUBBER:
        material_parameters = ([0.02, 0.02, 0.02], [0.01, 0.01, 0.01], [0.4, 0.4, 0.4], 10)
    elif material == MYGL_MATERIAL_CYAN_RUBBER:
        material_parameters = ([0.0, 0.05, 0.05], [0.4, 0.5, 0.5], [0.04, 0.7, 0.7], 10)
    elif material == MYGL_MATERIAL_GREEN_RUBBER:
        material_parameters = ([0.0, 0.05, 0.0], [0.4, 0.5, 0.4], [0.04, 0.7, 0.04], 10)
    elif material == MYGL_MATERIAL_RED_RUBBER:
        material_parameters = ([0.05, 0.0, 0.0], [0.5, 0.4, 0.4], [0.7, 0.04, 0.04], 10)
    elif material == MYGL_MATERIAL_WHITE_RUBBER:
        material_parameters = ([0.05, 0.05, 0.05], [0.5, 0.5, 0.5], [0.7, 0.7, 0.7], 10)
    elif material == MYGL_MATERIAL_YELLOW_RUBBER:
        material_parameters = ([0.05, 0.05, 0.0], [0.5, 0.5, 0.4], [0.7, 0.7, 0.04], 10)
    # Stones (precious, semi-precious, and non-precious)
    elif material == MYGL_MATERIAL_EMERALD:
        material_parameters = ([0.0215, 0.1745, 0.0215], [0.07568, 0.61424, 0.07568], [0.633, 0.727811, 0.633], 76.8)
    elif material == MYGL_MATERIAL_JADE:
        material_parameters = (
            [0.135, 0.2225, 0.1575, 0.95], [0.54, 0.89, 0.63, 0.95], [0.316228, 0.316228, 0.316228, 0.95], 12.8)
    elif material == MYGL_MATERIAL_OBSIDIAN:
        material_parameters = (
            [0.05375, 0.05, 0.06625, 0.82], [0.18275, 0.17, 0.22252, 0.82], [0.332741, 0.328634, 0.346435, 0.82], 38.4)
    elif material == MYGL_MATERIAL_PEARL:
        material_parameters = ([0.25, 0.20725, 0.20725], [1, 0.829, 0.829], [0.296648, 0.296648, 0.296648], 11.264)
    elif material == MYGL_MATERIAL_RUBY:
        material_parameters = (
            [0.1745, 0.01175, 0.01175], [0.61424, 0.04136, 0.04136], [0.727811, 0.626959, 0.626959], 76.8)
    elif material == MYGL_MATERIAL_TURQUOISE:
        material_parameters = ([0.1, 0.18725, 0.1745], [0.396, 0.74151, 0.69102], [0.297254, 0.30829, 0.306678], 12.8)
    # Made Up
    elif material == "Super Specular Gold":
        material_parameters = ([0.0, 0.0, 0.0, 1.0], [0.75164, 0.60648, 0.22648, 1.0], [1.0, 1.0, 1.0, 1.0], 64)
    # Misc.
    elif material == MYGL_MATERIAL_GLASS:
        material_parameters = ([0, 0, 0, 0], [0, 0, 0, 0], [1, 1, 1, 1], 32)
    elif material == MYGL_MATERIAL_NONE:
        material_parameters = ([0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], 32)
    elif material == MYGL_MATERIAL_FULL:
        material_parameters = ([1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], 128)
    else:  # material == MYGL_MATERIAL_DEFAULT:
        material_parameters = ([0.2, 0.2, 0.2, 1.0], [0.8, 0.8, 0.8, 1.0], [0, 0, 0, 1], 0)
    # [0.2,0.2,0.2,1.0],[0.8,0.8,0.4,1.0],[1,1,1,1],[0,0,0,1],128
    # http://www.sc.ehu.es/ccwgamoa/docencia/Material/OpenGL/Materials-Parameters/MaterialsParameters.htm
    # http://devernay.free.fr/cours/opengl/materials.html google "opengl materials"
    return material_parameters


def material_set(material):
    material_parameters = get_material_param(material)
    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, material_parameters[0])
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, material_parameters[1])
    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, material_parameters[2])
    # glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION, material_parameters[3])
    glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, material_parameters[3])


class RGBA(object):
    BLACK = (0, 0, 0, 1)
    WHITE = (1, 1, 1, 1)
    Colors = {}

    __slots__ = ['r', 'g', 'b', 'a']

    def __init__(self, r=None, g=None, b=None, a=None):
        if isinstance(r, RGBA):
            self.r = r.r
            self.g = r.g
            self.b = r.b
            self.a = r.a
        elif hasattr(r, "__getitem__"):
            self.r = r[0]
            self.g = r[1]
            self.b = r[2]
            self.a = r[3]
        else:
            self.r = 0.
            self.g = 0.
            self.b = 0.
            self.a = 1.
            if r is not None: self.r = r
            if g is not None: self.g = g
            if b is not None: self.b = b
            if a is not None: self.a = a

    def __len__(self): return 4

    def __getitem__(self, key):
        if key == 0: return self.r
        elif key == 1: return self.g
        elif key == 2: return self.b
        elif key == 3: return self.a
        else: raise IndexError("Invalid subscript " + str(key) + " to RGBA")

    def __setitem__(self, key, value):
        if key == 0: self.r = value
        elif key == 1: self.g = value
        elif key == 2: self.b = value
        elif key == 3: self.a = value
        else: raise IndexError("Invalid subscript " + str(key) + " to RGBA")

    # String representaion (for debugging)
    def __repr__(self):
        return 'RGBA(%s, %s, %s, %s)' % (self.r, self.g, self.b, self.a)

RGBA.Colors[0] = (0.0, 0.0, 0.0, 1.0)
RGBA.Colors[1] = (1.0, 1.0, 1.0, 1.0)
RGBA.Colors[2] = (1.0, 0.0, 0.0, 1.0)
RGBA.Colors[3] = (1.0, 1.0, 0.0, 1.0)
RGBA.Colors[4] = (1.0, 0.0, 1.0, 1.0)
RGBA.Colors[5] = (0.0, 1.0, 0.0, 1.0)
RGBA.Colors[6] = (0.0, 1.0, 1.0, 1.0)
RGBA.Colors[7] = (0.0, 0.0, 1.0, 1.0)
RGBA.Colors[8] = (0.5, 0.0, 0.0, 1.0)
RGBA.Colors[9] = (0.5, 0.5, 0.0, 1.0)
RGBA.Colors[10] = (0.5, 0.0, 0.5, 1.0)
RGBA.Colors[11] = (0.0, 0.5, 0.0, 1.0)
RGBA.Colors[12] = (0.0, 0.5, 0.5, 1.0)
RGBA.Colors[13] = (0.0, 0.0, 0.5, 1.0)
RGBA.Colors[14] = (1.0, 0.5, 0.0, 1.0)
RGBA.Colors[15] = (1.0, 0.0, 0.5, 1.0)
RGBA.Colors[16] = (0.5, 1.0, 0.0, 1.0)
RGBA.Colors[17] = (0.0, 1.0, 0.5, 1.0)
RGBA.Colors[18] = (0.5, 0.0, 1.0, 1.0)
RGBA.Colors[19] = (0.0, 0.5, 1.0, 1.0)
RGBA.Colors[20] = (1.0, 0.5, 0.5, 1.0)
RGBA.Colors[21] = (0.5, 1.0, 0.5, 1.0)
RGBA.Colors[22] = (0.5, 0.5, 1.0, 1.0)
RGBA.Colors[23] = (1.0, 1.0, 0.5, 1.0)
RGBA.Colors[24] = (1.0, 0.5, 1.0, 1.0)
RGBA.Colors[25] = (0.5, 1.0, 1.0, 1.0)
RGBA.Colors[26] = (0.1, 0.1, 0.1, 1.0)
RGBA.Colors[27] = (0.2, 0.2, 0.2, 1.0)
RGBA.Colors[28] = (0.3, 0.3, 0.3, 1.0)
RGBA.Colors[29] = (0.4, 0.4, 0.4, 1.0)
RGBA.Colors[30] = (0.5, 0.5, 0.5, 1.0)
RGBA.Colors[31] = (0.6, 0.6, 0.6, 1.0)
RGBA.Colors[32] = (0.7, 0.7, 0.7, 1.0)
RGBA.Colors[33] = (0.8, 0.8, 0.8, 1.0)
RGBA.Colors[34] = (0.9, 0.9, 0.9, 1.0)

for __idx in range(35, 256):
    RGBA.Colors[__idx] = (0.9, 0.9, 0.9, 1.0)


def load_texture(file_name=None, pixels=None, width=None, height=None,
                 detail=3, alpha=True, integer=False, max_lod=None):
    if file_name is not None:
        image = Image.open(file_name)
        width = image.size[0]
        height = image.size[1]

        pixels = image.tostring("raw", "RGBA" if alpha else "RGB", 0, -1)

    texture = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, texture)

    if detail == 0:
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
    elif detail == 1:
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
    elif detail == 2:
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    elif detail == 3:
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    elif detail == 4:
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    else:
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    # glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
    # glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)

    # glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
    # glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
    if max_lod is not None: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, max_lod)
    if alpha:
        if integer:
            target_format = GL_RGBA8UI
            source_format = GL_RGBA_INTEGER
        else:
            target_format = GL_RGBA8
            source_format = GL_RGBA
    else:
        if integer:
            target_format = GL_RGB8UI
            source_format = GL_RGB_INTEGER
        else:
            target_format = GL_RGB8
            source_format = GL_RGB
    glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE)
    glTexImage2D(GL_TEXTURE_2D, 0, target_format, width, height, 0, source_format, GL_UNSIGNED_BYTE, pixels)

    return texture, width, height


def glInitFog(fog_mode=GL_LINEAR, fog_color=(0.5, 0.5, 0.5, 0.5), fog_start=1.0, fog_end=100.0, use_ext=False):
    """fogMode=[GL_EXP, GL_EXP2, GL_LINEAR]"""
    if use_ext:
        glEnable(GL_FOG)  # // Enable Fog
        glFogi(GL_FOG_MODE, fog_mode)  # // Fog Fade Is Linear
        glFogfv(GL_FOG_COLOR, fog_color)  # // Set The Fog Color
        glFogf(GL_FOG_START, fog_start)  # // Set The Fog Start
        glFogf(GL_FOG_END, fog_end)  # // Set The Fog End
        glHint(GL_FOG_HINT, GL_NICEST)  # // Per-Pixel Fog Calculation
        glFogi(GL_FOG_COORDINATE_SOURCE_EXT, GL_FOG_COORDINATE_EXT)  # // Set Fog Based On Vertice Coordinates
        glInitFogCoordEXT()
    else:
        glFogi(GL_FOG_MODE, fog_mode)  # // Fog Mode
        glFogfv(GL_FOG_COLOR, fog_color)  # // Set Fog Color
        glFogf(GL_FOG_DENSITY, 0.1)  # // How Dense Will The Fog Be
        glHint(GL_FOG_HINT, GL_NICEST)  # // Fog Hint Value
        glFogf(GL_FOG_START, fog_start)  # // Fog Start Depth
        glFogf(GL_FOG_END, fog_end)  # // Fog End Depth
        glEnable(GL_FOG)  # // Enables GL_FOG


# We call this right after our OpenGL window is created.
def glInit(texture=True, light=True, blend=True, cull=True, depth=True, clear=RGBA.BLACK):
    if texture: glEnable(GL_TEXTURE_2D)  # // Enable Texture Mapping
    if light: glEnable(GL_LIGHTING)
    glEnable(GL_COLOR_MATERIAL)

    if blend:
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

    glClearColor(clear[0], clear[1], clear[2], clear[3])  # // Black Background

    glClearDepth(1.0)  # // Depth Buffer Setup
    if depth:
        glDepthFunc(GL_LEQUAL)  # // The Type Of Depth Testing
        glEnable(GL_DEPTH_TEST)  # // Enable Depth Testing
    if cull:
        glEnable(GL_CULL_FACE)
        glCullFace(GL_BACK)
        glFrontFace(GL_CCW)
    glEnable(GL_NORMALIZE)
    # glEnable(GL_RESCALE_NORMALS)
    glEnable(GL_POINT_SMOOTH)
    glEnable(GL_LINE_SMOOTH)
    glEnable(GL_POLYGON_SMOOTH)
    glShadeModel(GL_SMOOTH)  # // Select Smooth Shading
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)  # // Set Perspective Calculations To Most Accurate

